<template>
  <div class="container fade-in">
    <div class="header">
      <h2 class="section-title">优惠券包管理</h2>
      <div class="actions">
        <router-link to="/coupon-packages/edit" class="btn primary">
          <span class="icon" v-html="'➕'"></span>
          创建优惠券包
        </router-link>
      </div>
    </div>

    <!-- 统计卡片 -->
    <div class="grid kpi">
      <div class="card kpi slide-up" style="animation-delay: 0.1s">
        <div class="icon" style="background: var(--primary)" v-html="'📦'"></div>
        <div class="meta">
          <div class="label">优惠券包总数</div>
          <div class="value">{{ stats.totalPackages }}</div>
        </div>
      </div>
      <div class="card kpi slide-up" style="animation-delay: 0.2s">
        <div class="icon" style="background: var(--success)" v-html="'✅'"></div>
        <div class="meta">
          <div class="label">启用中</div>
          <div class="value">{{ stats.activePackages }}</div>
        </div>
      </div>
      <div class="card kpi slide-up" style="animation-delay: 0.3s">
        <div class="icon" style="background: var(--info)" v-html="'📤'"></div>
        <div class="meta">
          <div class="label">已领取</div>
          <div class="value">{{ stats.receivedCount }}</div>
        </div>
      </div>
      <div class="card kpi slide-up" style="animation-delay: 0.4s">
        <div class="icon" style="background: var(--warning)" v-html="'🎟️'"></div>
        <div class="meta">
          <div class="label">包含优惠券</div>
          <div class="value">{{ stats.totalCoupons }}</div>
        </div>
      </div>
    </div>

    <!-- 筛选和搜索 -->
    <div class="card filters slide-up" style="animation-delay: 0.5s">
      <div class="filter-row">
        <div class="field">
          <label>优惠券包名称</label>
          <input 
            v-model="filters.name" 
            class="input" 
            placeholder="搜索优惠券包名称"
            @input="debouncedSearch"
          />
        </div>
        <div class="field">
          <label>状态</label>
          <select v-model="filters.isActive" class="input" @change="loadPackages">
            <option value="">全部状态</option>
            <option :value="true">启用</option>
            <option :value="false">禁用</option>
          </select>
        </div>
        <div class="field">
          <button class="btn secondary" @click="resetFilters">重置</button>
        </div>
      </div>
    </div>

    <!-- 优惠券包列表 -->
    <div class="card slide-up" style="animation-delay: 0.6s">
      <div class="table-header">
        <h3 class="section-title">优惠券包列表</h3>
        <div class="table-actions">
          <button class="btn secondary sm" @click="loadPackages">
            <span class="icon">🔄</span>
            刷新
          </button>
        </div>
      </div>

      <div v-if="loading" class="loading-state">
        <div class="spinner"></div>
        <p>加载中...</p>
      </div>

      <div v-else-if="packages.length === 0" class="empty-state">
        <div class="empty-icon">📦</div>
        <h4>暂无优惠券包</h4>
        <p>还没有创建任何优惠券包，点击上方按钮创建第一个优惠券包</p>
      </div>

      <div v-else class="packages-grid">
        <div v-for="pkg in packages" :key="pkg.id" class="package-card">
          <div class="package-header">
            <h4>{{ pkg.name }}</h4>
            <div class="package-status">
              <span :class="['status-badge', pkg.isActive ? 'active' : 'inactive']">
                {{ pkg.isActive ? '启用' : '禁用' }}
              </span>
            </div>
          </div>
          
          <div class="package-content">
            <div class="package-description">
              <p>{{ pkg.description || '暂无描述' }}</p>
            </div>
            
            <div class="package-stats">
              <div class="stat-item">
                <span class="label">包含优惠券：</span>
                <span class="value">{{ pkg.couponCount || 0 }} 张</span>
              </div>
              <div class="stat-item">
                <span class="label">已领取：</span>
                <span class="value">{{ pkg.receiveCount || 0 }} 次</span>
              </div>
              <div class="stat-item">
                <span class="label">创建时间：</span>
                <span class="value">{{ formatDate(pkg.createdAt) }}</span>
              </div>
            </div>
          </div>
          
          <div class="package-actions">
            <router-link 
              :to="`/coupon-packages/detail/${pkg.id}`" 
              class="btn secondary sm"
            >
              查看详情
            </router-link>
            <router-link 
              :to="`/coupon-packages/edit/${pkg.id}`" 
              class="btn secondary sm"
            >
              编辑
            </router-link>
            <button 
              class="btn danger sm" 
              @click="confirmDelete(pkg)"
            >
              删除
            </button>
          </div>
        </div>
      </div>

      <!-- 分页 -->
      <div v-if="packages.length > 0" class="pagination">
        <button 
          class="btn secondary sm" 
          :disabled="pagination.pageIndex <= 1"
          @click="changePage(pagination.pageIndex - 1)"
        >
          上一页
        </button>
        <span class="page-info">
          第 {{ pagination.pageIndex }} 页，共 {{ Math.ceil(pagination.totalCount / pagination.pageSize) }} 页
        </span>
        <button 
          class="btn secondary sm" 
          :disabled="pagination.pageIndex >= Math.ceil(pagination.totalCount / pagination.pageSize)"
          @click="changePage(pagination.pageIndex + 1)"
        >
          下一页
        </button>
      </div>
    </div>

    <!-- 删除确认弹窗 -->
    <div v-if="showDeleteModal" class="modal-overlay" @click="closeDeleteModal">
      <div class="modal-content" @click.stop>
        <h3>确认删除</h3>
        <p>确定要删除优惠券包 "{{ packageToDelete?.name }}" 吗？此操作不可恢复。</p>
        <div class="modal-actions">
          <button class="btn secondary" @click="closeDeleteModal">取消</button>
          <button class="btn danger" @click="deletePackage">确认删除</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { 
  CouponService, 
  type CouponPackage, 
  type CouponPackageQueryRequest 
} from '../services/coupon'
import { isSuccess } from '../services/types'

// 原生 JavaScript 实现 debounce
function debounce<T extends (...args: any[]) => any>(func: T, delay: number): (...args: Parameters<T>) => void {
  let timeoutId: ReturnType<typeof setTimeout>
  return (...args: Parameters<T>) => {
    clearTimeout(timeoutId)
    timeoutId = setTimeout(() => func.apply(null, args), delay)
  }
}

const router = useRouter()

// 响应式数据
const loading = ref(false)
const packages = ref<CouponPackage[]>([])
const showDeleteModal = ref(false)
const packageToDelete = ref<CouponPackage | null>(null)

// 统计数据
const stats = reactive({
  totalPackages: 0,
  activePackages: 0,
  receivedCount: 0,
  totalCoupons: 0
})

// 筛选条件
const filters = reactive({
  name: '',
  isActive: '' as boolean | ''
})

// 分页信息
const pagination = reactive({
  pageIndex: 1,
  pageSize: 12,
  totalCount: 0
})

// 防抖搜索
const debouncedSearch = debounce(() => {
  pagination.pageIndex = 1
  loadPackages()
}, 500)

// 加载优惠券包列表
async function loadPackages() {
  try {
    loading.value = true
    
    const params: CouponPackageQueryRequest = {
      pageIndex: pagination.pageIndex,
      pageSize: pagination.pageSize,
      name: filters.name || undefined,
      isActive: filters.isActive === '' ? undefined : filters.isActive
    }
    
    const result = await CouponService.getPackageList(params)
    
    if (result.code === 0 && result.data) {
      packages.value = result.data.data || []
      pagination.totalCount = result.data.total || 0
      
      // 更新统计数据
      updateStats()
    } else {
      console.error('加载优惠券包失败:', result.message)
      packages.value = []
    }
  } catch (error) {
    console.error('加载优惠券包出错:', error)
    packages.value = []
  } finally {
    loading.value = false
  }
}

// 更新统计数据
function updateStats() {
  stats.totalPackages = pagination.totalCount
  stats.activePackages = packages.value.filter(pkg => pkg.isActive).length
  stats.receivedCount = packages.value.reduce((sum, pkg) => sum + (pkg.receiveCount || 0), 0)
  stats.totalCoupons = packages.value.reduce((sum, pkg) => sum + (pkg.couponCount || 0), 0)
}

// 重置筛选条件
function resetFilters() {
  filters.name = ''
  filters.isActive = ''
  pagination.pageIndex = 1
  loadPackages()
}

// 切换页面
function changePage(page: number) {
  pagination.pageIndex = page
  loadPackages()
}

// 确认删除
function confirmDelete(pkg: CouponPackage) {
  packageToDelete.value = pkg
  showDeleteModal.value = true
}

// 关闭删除弹窗
function closeDeleteModal() {
  showDeleteModal.value = false
  packageToDelete.value = null
}

// 删除优惠券包
async function deletePackage() {
  if (!packageToDelete.value?.id) return
  
  try {
    const result = await CouponService.deletePackage(packageToDelete.value.id)
    
    if (isSuccess(result)) {
      // 删除成功，重新加载列表
      await loadPackages()
      closeDeleteModal()
    } else {
      alert('删除失败：' + result.message)
    }
  } catch (error) {
    console.error('删除优惠券包出错:', error)
    alert('删除失败，请稍后重试')
  }
}

// 格式化日期
function formatDate(dateStr?: string): string {
  if (!dateStr) return '-'
  return new Date(dateStr).toLocaleDateString('zh-CN')
}

// 组件挂载时加载数据
onMounted(() => {
  loadPackages()
})
</script>

<style scoped>
.container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.section-title {
  font-size: 24px;
  font-weight: 600;
  color: var(--text-primary);
  margin: 0;
}

.actions {
  display: flex;
  gap: 12px;
}

.btn {
  display: inline-flex;
  align-items: center;
  gap: 8px;
  padding: 8px 16px;
  border: none;
  border-radius: 6px;
  font-size: 14px;
  font-weight: 500;
  text-decoration: none;
  cursor: pointer;
  transition: all 0.2s ease;
}

.btn.primary {
  background: var(--primary);
  color: white;
}

.btn.primary:hover {
  background: var(--primary-dark);
}

.btn.secondary {
  background: var(--bg-secondary);
  color: var(--text-primary);
  border: 1px solid var(--border);
}

.btn.secondary:hover {
  background: var(--bg-tertiary);
}

.btn.danger {
  background: var(--danger);
  color: white;
}

.btn.danger:hover {
  background: var(--danger-dark);
}

.btn.sm {
  padding: 6px 12px;
  font-size: 12px;
}

.btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.grid.kpi {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
  gap: 20px;
  margin-bottom: 24px;
}

.card {
  background: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  border: 1px solid var(--border);
}

.card.kpi {
  display: flex;
  align-items: center;
  gap: 16px;
  padding: 16px 20px;
}

.card.kpi .icon {
  width: 48px;
  height: 48px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 20px;
  color: white;
}

.card.kpi .meta .label {
  font-size: 14px;
  color: var(--text-secondary);
  margin-bottom: 4px;
}

.card.kpi .meta .value {
  font-size: 24px;
  font-weight: 600;
  color: var(--text-primary);
}

.filters {
  margin-bottom: 24px;
}

.filter-row {
  display: flex;
  gap: 16px;
  align-items: end;
  flex-wrap: wrap;
}

.field {
  display: flex;
  flex-direction: column;
  gap: 4px;
  min-width: 200px;
}

.field label {
  font-size: 14px;
  font-weight: 500;
  color: var(--text-primary);
}

.input {
  padding: 8px 12px;
  border: 1px solid var(--border);
  border-radius: 6px;
  font-size: 14px;
  background: white;
  transition: border-color 0.2s ease;
}

.input:focus {
  outline: none;
  border-color: var(--primary);
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.table-header .section-title {
  font-size: 18px;
}

.table-actions {
  display: flex;
  gap: 8px;
}

.loading-state, .empty-state {
  text-align: center;
  padding: 60px 20px;
  color: var(--text-secondary);
}

.spinner {
  width: 32px;
  height: 32px;
  border: 3px solid var(--border);
  border-top: 3px solid var(--primary);
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin: 0 auto 16px;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.empty-icon {
  font-size: 48px;
  margin-bottom: 16px;
}

.packages-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
  gap: 20px;
  margin-bottom: 24px;
}

.package-card {
  border: 1px solid var(--border);
  border-radius: 8px;
  padding: 20px;
  background: white;
  transition: all 0.2s ease;
}

.package-card:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  transform: translateY(-2px);
}

.package-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 16px;
}

.package-header h4 {
  font-size: 16px;
  font-weight: 600;
  color: var(--text-primary);
  margin: 0;
  flex: 1;
}

.package-status {
  margin-left: 12px;
}

.status-badge {
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 500;
}

.status-badge.active {
  background: var(--success-light);
  color: var(--success);
}

.status-badge.inactive {
  background: var(--warning-light);
  color: var(--warning);
}

.package-content {
  margin-bottom: 16px;
}

.package-description {
  margin-bottom: 12px;
}

.package-description p {
  font-size: 14px;
  color: var(--text-secondary);
  margin: 0;
  line-height: 1.5;
}

.package-stats {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.stat-item {
  display: flex;
  justify-content: space-between;
  font-size: 14px;
}

.stat-item .label {
  color: var(--text-secondary);
}

.stat-item .value {
  color: var(--text-primary);
  font-weight: 500;
}

.package-actions {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.pagination {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 16px;
  margin-top: 24px;
}

.page-info {
  font-size: 14px;
  color: var(--text-secondary);
}

.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.modal-content {
  background: white;
  border-radius: 8px;
  padding: 24px;
  max-width: 400px;
  width: 90%;
  max-height: 90vh;
  overflow-y: auto;
}

.modal-content h3 {
  margin: 0 0 16px 0;
  font-size: 18px;
  color: var(--text-primary);
}

.modal-content p {
  margin: 0 0 24px 0;
  color: var(--text-secondary);
  line-height: 1.5;
}

.modal-actions {
  display: flex;
  gap: 12px;
  justify-content: flex-end;
}

/* 动画效果 */
.fade-in {
  animation: fadeIn 0.3s ease-out;
}

.slide-up {
  animation: slideUp 0.4s ease-out;
}

@keyframes fadeIn {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}

@keyframes slideUp {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 响应式设计 */
@media (max-width: 768px) {
  .container {
    padding: 16px;
  }
  
  .header {
    flex-direction: column;
    gap: 16px;
    align-items: stretch;
  }
  
  .filter-row {
    flex-direction: column;
  }
  
  .field {
    min-width: auto;
  }
  
  .packages-grid {
    grid-template-columns: 1fr;
  }
  
  .package-actions {
    justify-content: center;
  }
  
  .pagination {
    flex-direction: column;
    gap: 8px;
  }
}
</style>
